import {createRouter, createWebHistory} from 'vue-router'
import request from '@/http/request'
import AdminLayout from '@/components/layout/AdminLayout'
import {ElMessage} from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/Index'),
  },

  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login'),
    meta: {
      title: '登陆',
    },
  },

  {
    path: '/return',
    name: 'return',
    component: () => import('@/views/Return'),
    meta: {
      title: '支付结果',
    },
  },

  {
    path: '/admin',
    name: 'adminLayout',
    component: AdminLayout,
    redirect: '/admin/dashboard',
    children: [
      {
        path: '/admin/dashboard',
        name: 'dashboard',
        component: () => import('@/views/admin/Dashboard'),
        meta: {
          title: '仪表盘',
        },
      },
      {
        path: '/admin/profile',
        name: 'profile',
        component: () => import('@/views/admin/Profile'),
        meta: {
          title: '修改资料',
        },
      },
      {
        path: '/admin/donation',
        name: 'adminDonation',
        component: () => import('@/views/admin/Donation'),
        meta: {
          title: '捐赠列表',
        },
      },
      {
        path: '/admin/type',
        name: 'type',
        component: () => import('@/views/admin/Type'),
        meta: {
          title: '支付方式管理',
        },
      },
    ],
    beforeEnter(to, from, next) {
      request.getLoginStatus().then(response => {
        if (response.status === 200) {
          localStorage.setItem('username', response.data.result.username)
          next()
        }
      }).catch(error => {
        console.log(error.message)
        if (error.response.status === 401) {
          ElMessage.error('您的登陆状态已失效，请重新登陆')
        }
        next({name: 'login'})
      })
    },
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {

  //获取siteName
  if (localStorage.getItem('siteName') === null) {
    request.getSiteName().then((response) => {
      localStorage.setItem('siteName', response.data.result.siteName)
      document.title = response.data.result.siteName
    })
  }
  document.title = localStorage.getItem('siteName')

  //拼接路由上的名字
  if (!(to.meta.title === undefined)) {
    document.title = to.meta.title + ' - ' + localStorage.getItem('siteName')
  }
  next()
})

export default router
